package com.ophiux.utils.wechat;

import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class ParseXmlUtil {
	
	
	/**
	 * 创建Xstream实例
	 */
	public  static XStream xstream = new XStream(new XppDriver(){
		
		public HierarchicalStreamWriter createWriter(Writer out){
			return new PrettyPrintWriter(out){
				//对所有xml节点都增加CDATA标记
				boolean cdata = true;
				
				public void startNode(String name,Class clz){
					super.startNode(name,clz);
				}
				
				protected void writeText(QuickWriter writer,String text){
					if(cdata){
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					}else{
						writer.write(text);
					}
				}
				
			};
			
		}
	});
	
	/**
	 * 将对象组建成xml格式
	 * @param obj
	 * @return
	 */
	public static String parseObjectToXmlString(Object obj) {
		StringBuffer result  = new StringBuffer("<xml>");
		if(obj != null) {
			Field[] fields = obj.getClass().getDeclaredFields();
			for(Field field : fields) {
				field.setAccessible(true);
				try {
					if(field.get(obj) != null && !field.get(obj).equals("")) {
						result.append("<"+field.getName()+">"+field.get(obj)+"</"+field.getName()+">");
						
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		result.append("</xml>");
		return result.toString();
	}
	
	/**
	 * 将对象转换成字符串参数 格式为key=value形式 
	 * @param obj
	 * @return  name1=value1&name2=value2
	 */
	public static String parseObjectToSpecifyString(Object obj) {
		StringBuffer result  = new StringBuffer("");
		if(obj != null) {
			Field[] fields = obj.getClass().getDeclaredFields();
			for(int i=0;i<fields.length;i++) {
				Field field = fields[i];
				field.setAccessible(true);
				try {
					if(field.get(obj) != null && !field.get(obj).equals("")) {
						result.append(field.getName()+"="+field.get(obj)+"&");
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				
			}
		}
		String return_result = result.toString().substring(0, result.toString().length()-1);
		return return_result;
	}
	public static Object parseXmlStringToObject(String xml,Class<?> cls) {
		Object obj = null;
		try {
			obj = cls.newInstance();
			Map map = WXServiceUtils.doXMLParse(xml);
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = (String) map.get(key);
				//System.out.println("key:"+key+" value="+value);
				Method method = cls.getMethod("set"
						+ key.substring(0, 1).toUpperCase() + key.substring(1),
						String.class);
				System.out.println("method name:" + method.getName());
				method.invoke(obj, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 微信通知返回参数
	 * @param return_code
	 * @param return_msg
	 * @return
	 */
	public static String setWeiXinNotifyReturnXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
	}
	

	
	public static String parseObjectToXmlString11(Object obj) {
		StringBuffer result  = new StringBuffer("<xml>");
		if(obj != null) {
			Field[] fields = obj.getClass().getDeclaredFields();
			for(Field field : fields) {
				field.setAccessible(true);
				try {
					if(field.get(obj) != null && !field.get(obj).equals("")) {
						result.append("<"+field.getName()+">"+field.get(obj)+"</"+field.getName()+">");
						
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		result.append("</xml>");
//		System.out.println();
		return result.toString();
	}
	
	public static void main(String[] args) throws Exception {
		String str = "<xml>" +
				"<appid><![CDATA[wx5cd4289998a5e8db]]></appid>" +
				"<bank_type><![CDATA[CFT]]></bank_type>" +
				"<cash_fee><![CDATA[100]]></cash_fee>" +
				"<fee_type><![CDATA[CNY]]></fee_type>" +
				"<is_subscribe><![CDATA[N]]></is_subscribe>" +
				"<mch_id><![CDATA[1333741001]]></mch_id>" +
				"<nonce_str><![CDATA[1015585994]]></nonce_str>" +
				"<openid><![CDATA[o5gLHvmv6LYC_0uUpIXDlKLnMReQ]]></openid>" +
				"<out_trade_no><![CDATA[9001201605201015056]]></out_trade_no>" +
				"<result_code><![CDATA[SUCCESS]]></result_code>" +
				"<return_code><![CDATA[SUCCESS]]></return_code>" +
				"<sign><![CDATA[2B0004488ECEBC708F2D977222E8C5EF]]></sign>" +
				"<time_end><![CDATA[20160520101610]]></time_end>" +
				"<total_fee>100</total_fee>" +
				"<trade_type><![CDATA[APP]]></trade_type>" +
				"<transaction_id><![CDATA[4008012001201605206058193001]]></transaction_id>" +
				"</xml>";
	}
}
